import static_gesture_bp as bp
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader

data_1 = np.loadtxt('其它.txt')
data_2 = np.loadtxt('图案1.txt')
data_3 = np.loadtxt('图案2.txt')

def data_tf(x):
    x = np.array(x,dtype='float32')/4000
    x = (x-0.5)/0.5
    x = torch.from_numpy(x)
    return x

data_1 = data_tf(data_1[:,1:10].reshape(int((data_1.shape[0]/13)),-1))
data_2 = data_tf(data_2[:,1:10].reshape(int((data_2.shape[0]/13)),-1))
data_3 = data_tf(data_3[:,1:10].reshape(int((data_3.shape[0]/13)),-1))

label_1 = np.tile(np.array([0],dtype='float32'),(data_1.shape[0],1))
label_2 = np.tile(np.array([1],dtype='float32'),(data_2.shape[0],1))
label_3 = np.tile(np.array([2],dtype='float32'),(data_3.shape[0],1))

data_1 = np.append(data_1,label_1,axis=1)
data_2 = np.append(data_2,label_2,axis=1)
data_3 = np.append(data_3,label_3,axis=1)

data = np.append(data_1,data_2,axis=0)
data = np.append(data,data_3,axis=0)

net_1 = bp.bp_net(117,80,30,8,3)

tran_data = DataLoader(data,batch_size=16,shuffle=True)

optim = torch.optim.SGD(net_1.parameters(),0.01)
crea = nn.CrossEntropyLoss()

for e in range(30):
    tran_loss = 0
    tran_acc = 0
    net_1.train()
    for data_t in tran_data:
        da = Variable(data_t[:,0:117])
        label = Variable(data_t[:,117].type(torch.int64))
        out = net_1.forward(da)
        optim.zero_grad()
        loss = crea(out,label)
        loss.backward()
        optim.step()
        #误差记录
        tran_loss += loss.data
        _,pred = out.max(1)
        num_correct = (pred == label).sum().data
        acc = num_correct / da.shape[0]
        tran_acc += acc
    print('loss:{:.6f},acc:{:.6f}'.format(tran_loss/len(tran_data),tran_acc/len(tran_data)))
#保存模型参数
torch.save(net_1.state_dict(),'static1.pth')








